﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Data;
using KorleBu.Application_Classes;
using System.Web.Security;

namespace KorleBu
{
    public partial class Login : System.Web.UI.Page
    {
        #region Class State Variables
        /// <summary>
        /// Dataset object, used for housing login method calls results.
        /// </summary>
        DataSet ds = new DataSet();
        /// <summary>
        /// Presentation object that accesses the presentation object classes methods.
        /// Used for accessing business methods for the login page.
        /// </summary>
        Presentation presentation = new Presentation();
        /// <summary>
        /// Represents the salt and password hash that was created using the createHashedPassword().
        /// </summary>
        //string[] hashWithSalt;
        #endregion

        #region Methods
        /// <summary>
        /// Page load method, gets run at the start of the page.
        /// Sets the Login error label to the initial empty state.
        /// </summary>
        /// <param name="sender">object</param>
        /// <param name="e">EventArgs</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            lblLoginError.Text = ""; // Clear any old errors
            txtUserName.Focus();
        }
        /// <summary>
        /// Method handles the login button functionality.  Logs in a user, if there are errors, an appropriate message is displayed.
        /// Otherwise, with a successful login the user is redirected to the home page.
        /// </summary>
        /// <param name="sender">object</param>
        /// <param name="e">ImageClickEventArgs</param>
        protected void login_Click(object sender, EventArgs e)
        {
            String IP = GetMyIp();      //Get the IP address

            ////retrieve this user's salt from the database
            //ds = presentation.GetSaltByUserName(txtUserName.Text);

            //if (ds.Tables.Count > 0) //if the method returned successfully
            //{
            //    if (ds.Tables[0].Rows[0][0].ToString() != "") //if errors have occurred
            //    {
            //        lblLoginError.Text = ds.Tables[0].Rows[0][0].ToString();    //Error Message
            //    }
            //    else
            //    {
            //        string dbSalt = ds.Tables[1].Rows[0][0].ToString();     //assign the salt string to what is returned from the database

            //        //create hashed password and send in the hashed password to the database.
            //        hashWithSalt = PasswordHash.createHashedPassword(txtPassword.Text, dbSalt);

                    //try to login in
                    String password = FormsAuthentication.HashPasswordForStoringInConfigFile(txtPassword.Text, "SHA1");
                    ds = presentation.Login(txtUserName.Text, password, IP);
                    //ds = presentation.Login(txtUserName.Text, hashWithSalt[1], IP);

                    //check to see if the user name is a valid user name in database, if so return the user's salt for the password.
                    if (ds.Tables.Count > 0) // If the method returned successfully
                    {
                        if (ds.Tables[0].Rows[0][0].ToString() != "") // if errors have occurred
                        {
                            lblLoginError.Text = ds.Tables[0].Rows[0][0].ToString(); // Error message
                        }
                        else
                        {
                            //counter an errors if any arise, otherwise log in the user and redirect to the home page.
                            if (ds.Tables.Count > 0) // If the method returned successfully
                            {
                                if (ds.Tables[0].Rows[0][0].ToString() != "") // if errors have occurred
                                {
                                    lblLoginError.Text = ds.Tables[0].Rows[0][0].ToString(); // Error message
                                }
                                else
                                {
                                    //set global user object's class fields to database return results, this will allow access to user account info throughout application.
                                    
                                    
                                    Session["LoggedInUser"] = new User();
                                    User lg = (User)Session["LoggedInUser"];
                                    lg.setSessionId(ds.Tables[1].Rows[0][4].ToString());
                                    lg.setUserId(Convert.ToInt32(ds.Tables[1].Rows[0][0].ToString()));
                                    lg.setUserName(txtUserName.Text);
                                    lg.setFirstName(ds.Tables[1].Rows[0][1].ToString());
                                    lg.setLastName(ds.Tables[1].Rows[0][2].ToString());
                                    if (String.IsNullOrEmpty(ds.Tables[1].Rows[0][3].ToString()))
                                    {
                                        lg.setStoreId(-1);
                                    }
                                    else
                                    {
                                        lg.setStoreId(Convert.ToInt32(ds.Tables[1].Rows[0][3].ToString()));
                                    }
                                    //Booleans for Role IDs and Status ID
                                    lg.setIsAdmin(Convert.ToBoolean(ds.Tables[1].Rows[0][5].ToString()));
                                    lg.setIsGeneralManager(Convert.ToBoolean(ds.Tables[1].Rows[0][6].ToString()));
                                    lg.setIsStoreManager(Convert.ToBoolean(ds.Tables[1].Rows[0][7].ToString()));
                                    lg.setIsStoreKeeper(Convert.ToBoolean(ds.Tables[1].Rows[0][8].ToString()));
                                    lg.setIsSubUnitClerk(Convert.ToBoolean(ds.Tables[1].Rows[0][9].ToString()));
                                    lg.setIsCEO(Convert.ToBoolean(ds.Tables[1].Rows[0][10].ToString()));
                                    lg.setIsAccounting(Convert.ToBoolean(ds.Tables[1].Rows[0][11].ToString()));
                                    lg.setIsProcurement(Convert.ToBoolean(ds.Tables[1].Rows[0][12].ToString()));
                                    //lg.setEmail(ds.Tables[1].Rows[0][13].ToString());
                                    lg.setStatusId(20);
                                    Session["LoggedInUser"] = lg;
                                    // Redirect the user to the Requests page for satellite users, the requisitions page for GM and CEO
                                    if (Convert.ToBoolean(ds.Tables[1].Rows[0][9].ToString()))
                                    {
                                        Response.Redirect("~/Requests.aspx", false); // All clear, go to next page
                                    }
                                    else if (Convert.ToBoolean(ds.Tables[1].Rows[0][10].ToString()) || Convert.ToBoolean(ds.Tables[1].Rows[0][12].ToString()) || Convert.ToBoolean(ds.Tables[1].Rows[0][6].ToString()))
                                    {
                                        Response.Redirect("~/Requisitions.aspx", false); // All clear, go to next page
                                    }
                                    else
                                    {
                                        Response.Redirect("~/Home.aspx", false); // All clear, go to next page
                                    }
                                }
                            }
                            else
                                lblLoginError.Text = "Invalid User or Password"; // If the Data Tier cannot be reached
                        }
                    }
                    else
                        lblLoginError.Text = "Invalid Username or Password"; // If the Data Tier cannot be reached
            //    }
            //}
            //else
            //    lblLoginError.Text = "Sorry, the system could not log you in.";     //If the Data Tier cannot be reached
        }
        /// <summary>
        /// Method handles when the forgot password link is pressed.  Retrieves the user's password hint from the database.
        /// </summary>
        /// <param name="sender">object</param>
        /// <param name="e">EventArgs</param>
        protected void btnForgotPassword_Click(object sender, EventArgs e)
        {
            //Reset the error labels to blank
            lblError.Text = "";
            lblLoginError.Text = "";
            //Create a dataset to return the response from the get hint presentation class method.
            //Retrieve the hint, if an error occurred, handle appropriately, otherwise set the lblLoginError to the password hint.  
            //lblLoginError is used for both positive and negative returns since it is nicely placed on the page.
            ds = presentation.GetHint(txtUserName.Text);

            if (ds.Tables.Count > 0) // If the method returned successfully
            {
                if (ds.Tables[0].Rows[0][0].ToString() != "") // if errors have occurred
                {
                    lblLoginError.Text = ds.Tables[0].Rows[0][0].ToString(); // Error message
                }
                else
                {
                    lblLoginError.Text = "Password Hint: " + ds.Tables[1].Rows[0][0].ToString();
                }
            }
            else
                lblLoginError.Text = "Sorry, the system could not retrieve your password hint.  Contact a system administrator."; // If the Data Tier cannot be reached
        }
        /// <summary>
        /// Method returns the IP address for the current user trying to log in
        /// </summary>
        /// <returns>String-IP address</returns>
        public static String GetMyIp()
        {
            String myIp = "";
            IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());     //Get the host IP Addresses
            //find the internetwork IP address, then assign that IP address to the return string.
            foreach (IPAddress ip in host.AddressList)
            {
                if (ip.AddressFamily.ToString() == "InterNetwork")
                {
                    myIp = ip.ToString();
                }
            }

            return myIp;
        }

        #endregion
    }
}